package com.wlient.basic.Thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThreadLocal
{
    private static ThreadLocal<StringBuilder> builder = ThreadLocal.withInitial(StringBuilder::new);

//    public static void main(String[] args)
//    {
//        for (int i = 0; i < 5; i++)
//        {
//            new Thread(() -> {
//                String threadName = Thread.currentThread().getName();
//                for (int j = 0; j < 3; j++)
//                {
//                    append(j);
//                    System.out.printf("%s append %d, now builder value is %s, ThreadLocal instance hashcode is %d, ThreadLocal instance mapping value hashcode is %d\n", threadName, j, builder.get().toString(), builder.hashCode(), builder.get().hashCode());
//                }
//
//                change();
//                System.out.printf("%s set new stringbuilder, now builder value is %s, ThreadLocal instance hashcode is %d, ThreadLocal instance mapping value hashcode is %d\n", threadName, builder.get().toString(), builder.hashCode(), builder.get().hashCode());
//            }, "thread-" + i).start();
//        }
//    }

    private static void append(int num) {
        builder.get().append(num);
    }

    private static void change() {
        StringBuilder newStringBuilder = new StringBuilder("HelloWorld");
        builder.set(newStringBuilder);

    }
    public static void main(String[] args) {
        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        // 创建一个有2个核心线程数的线程池
        ExecutorService threadPool = new ThreadPoolExecutor(1, 3, 1, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10));
        // 线程池提交一个任务，将任务序号及执行该任务的子线程的线程名放到 ThreadLocal 中
        threadPool.execute(() -> threadLocal.set("任务1: " + Thread.currentThread().getName()));
        threadPool.execute(() -> threadLocal.set("任务2: " + Thread.currentThread().getName()));
        threadPool.execute(() -> threadLocal.set("任务3: " + Thread.currentThread().getName()));
        // 输出 ThreadLocal 中的内容
        for (int i = 0; i < 10; i++) {
            threadPool.execute(() -> System.out.println("ThreadLocal value of " + Thread.currentThread().getName() + " = " + threadLocal.get()));
        }
        // 线程池记得关闭
        threadPool.shutdown();
    }
}